package com.baymax.test.scene.demo

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams
import android.widget.FrameLayout
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.get
import androidx.core.widget.NestedScrollView
import com.baymax.test.scene.BaseGroupScene
import com.baymax.test.scene.BaseScene
import com.baymax.test.scene.addButton
import com.baymax.test.scene.addDFView
import com.baymax.test.scene.newSceneFlexContainer
import com.bytedance.scene.Scene
import com.bytedance.scene.ktx.replace
import com.google.android.flexbox.FlexboxLayout
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlin.properties.Delegates

class TextHeightScene : BaseGroupScene() {

    override fun onCreateView(p0: LayoutInflater, p1: ViewGroup, p2: Bundle?): ViewGroup {
        return p1.newSceneFlexContainer {
            val childId = View.generateViewId()
            addButton("text size") {
                replace(childId, TextSizeScene(), "demo")
            }
            addButton("gravity") {
                replace(childId, GravityDemo(), "demo")
            }
            addButton("custom draw text") {
                replace(childId, CustomTextDemo(), "demo")
            }

            val child = FrameLayout(context)
            child.id = childId
            addView(
                child,
                FlexboxLayout.LayoutParams.MATCH_PARENT,
                FlexboxLayout.LayoutParams.WRAP_CONTENT
            )
        }
    }


    class CustomTextDemo : BaseScene() {
        override fun onCreateView(p0: LayoutInflater, p1: ViewGroup, p2: Bundle?): View {
            val index = MutableStateFlow(10)

            return p1.newSceneFlexContainer {
                clipChildren = false
                clipToPadding = false
                val scrollView = HorizontalScrollView(p1.context).apply {
                    clipChildren = false
                    clipToPadding = false
                }
                val ll: LinearLayout = object : LinearLayout(p1.context) {
                    init {
                        orientation = LinearLayout.HORIZONTAL
                    }

                    val txtPain = Paint(Paint.ANTI_ALIAS_FLAG).apply {
                        setColor(Color.RED)
                        textSize = 36f
                    }
                    val s = " Top / Right "
                    val mw = txtPain.measureText(s)
                    override fun dispatchDraw(canvas: Canvas) {
                        super.dispatchDraw(canvas)
                        getChildAt(index.value)?.let {
                            canvas.drawText(
                                s,
                                it.right - mw / 2f,
                                it.top + txtPain.textSize / 2f - 1f,
                                txtPain
                            )
                        }
                    }

                }.apply {
                    clipChildren = false
                    clipToPadding = false
                }
                scrollView.addView(ll)
                addDFView(LayoutParams.MATCH_PARENT, -2, scrollView)
                (0..20).forEach {
                    ll.addView(
                        createChild(p1.context, it),
                        LinearLayout.LayoutParams(200, 100)
                    )
                }
                addButton("+1") {
                    index.value += 1
                }
                addButton("-1") {
                    index.value -= 1
                }
                launch {
                    index.collectLatest {
                        ll.getChildAt(it)?.let {
                            scrollView.scrollTo( it.left ,0)
                        }
                        ll.postInvalidate()
                    }
                }
            }
        }

        private fun createChild(context: Context, i: Int): View {
            return object : View(context) {

                val txtPain = Paint(Paint.ANTI_ALIAS_FLAG).apply {
                    setColor(Color.RED)
                    textSize = 36f
                }

                override fun onDraw(canvas: Canvas) {
                    super.onDraw(canvas)
                    val w = width
                    val h = height
                    canvas.drawText("$i", width / 2f, height / 2f, txtPain)

                }

            }

        }
    }

    class TextSizeScene : BaseScene() {
        override fun onCreateView(
            p0: LayoutInflater,
            p1: ViewGroup,
            p2: Bundle?
        ): View {
            return p1.newSceneFlexContainer {


                setPadding(60, 60, 60, 60)
                val ctx = p1.context
                val text = @SuppressLint("AppCompatCustomView")
                object : TextView(ctx) {


                    override fun onDraw(canvas: Canvas) {
                        super.onDraw(canvas)
                        // 计算Baseline绘制的起点X轴坐标 ，计算方式：画布宽度的一半 - 文字宽度的一半
                        // 计算Baseline绘制的起点X轴坐标 ，计算方式：画布宽度的一半 - 文字宽度的一半
//                    val baseX = (canvas!!.width / 2 - mTextPaint.measureText(TEXT) / 2) as Int

                        // 计算Baseline绘制的Y坐标 ，计算方式：画布高度的一半 - 文字总高度的一半
                        // 计算Baseline绘制的Y坐标 ，计算方式：画布高度的一半 - 文字总高度的一半
                        val baseY =
                            (height / 2f - (paint.descent() + paint.ascent()) / 2f)

                        canvas?.drawLine(0f, baseY - 1, width.toFloat(), baseY + 1, paint)

                    }
                }
                val p = text.paint
                Log.d(TAG, "onCreateView: p.fm ${p.fontMetrics}")
                text.gravity = Gravity.CENTER
                val gen: (Int) -> String =
                    { s -> "abcdefghiglkyw 免费、生活、电视剧、影视会员: $s" }
                text.text = gen(24)
                text.includeFontPadding = false
                val tx = FlexboxLayout.LayoutParams(LayoutParams.WRAP_CONTENT, -2)
                addView(text, tx)
                val box = View(ctx)
                val fx = FlexboxLayout.LayoutParams(24, 24)
                box.background = ColorDrawable(Color.GREEN)
                addView(box, fx)


                val units = listOf(
                    TypedValue.COMPLEX_UNIT_PX, TypedValue.COMPLEX_UNIT_PT,
                    TypedValue.COMPLEX_UNIT_DIP, TypedValue.COMPLEX_UNIT_SP
                )
                var size: Float by Delegates.observable(24f) { _, o, n ->
                    Log.d(TAG, "onCreateView: $o -> $n")
                    text.setTextSize(TypedValue.COMPLEX_UNIT_PX, n * 0.9f)
                    text.text = gen(n.toInt())
                    text.post {
                        Log.d(TAG, "onCreateView: post H ${text.height}")
                    }
                    tx.height = n.toInt()
                    fx.height = n.toInt()
                    box.layoutParams = fx
                }


                addButton("+") {
                    Log.d(TAG, "onCreateView: $text ， ${text.textSize}")
                    size += 1f
                }

                addButton("-") {
                    size -= 1f
                }

                var unit by Delegates.observable(units.first()) { p, o, n ->
                    text.setTextSize(n, size)
                }
                addButton("unit ") {
                    unit = units.getOrNull(units.indexOf(unit) + 1) ?: units.first()
                    Log.d(TAG, "onCreateView: unit $unit")

                }

            }
        }

    }

    fun GravityDemo(): Scene {
        return object : BaseScene() {
            override fun onCreateView(
                p0: LayoutInflater,
                p1: ViewGroup,
                p2: Bundle?
            ): View = p1.newSceneFlexContainer {
                val txt = addDFView<TextView>(300, 80, TextView(p1.context)) {
                    setText("这是超出后可以滚动的文本这是超出后可以滚动的文本这是超出后可以滚动的文本这是超出后可以滚动的文本")
                    gravity = Gravity.CENTER
                    maxLine = 1
                    isSingleLine = true
                    ellipsize = TextUtils.TruncateAt.END
                }

                addButton("center") {
                    txt.gravity = Gravity.CENTER
                }
                addButton("CENTER_VERTICAL") {
                    txt.gravity = Gravity.CENTER_VERTICAL
                }
                addButton("CENTER_HORIZONTAL") {
                    txt.gravity = Gravity.CENTER_HORIZONTAL
                }
                addButton("START|CENTER_VERTICAL") {
                    txt.gravity = Gravity.START or Gravity.CENTER_VERTICAL
                }
                addButton("START") {
                    txt.gravity = Gravity.START
                }
                addButton("END") {
                    txt.gravity = Gravity.END
                }
                addButton("center") {
                    txt.gravity = Gravity.CENTER
                }
            }

        }
    }
}